package com.hanbang.taitaigou.ui.activity.aboutme.address;

import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.Poi;
import com.hanbang.taitaigou.R;
import com.hanbang.taitaigou.ui.activity.base.BaseActivity;
import com.hanbang.taitaigou.ui.activity.home.AddAddressActivity;
import com.hanbang.taitaigou.ui.widget.dialog.BaseDialog;
import com.hanbang.taitaigou.ui.widget.dialog.OnClickCallback;
import com.hanbang.taitaigou.utils.http.HttpCallBack;
import com.hanbang.taitaigou.utils.http.HttpRequestParams;
import com.hanbang.taitaigou.utils.other.EditHelper;
import com.hanbang.taitaigou.utils.other.StringUtils;
import com.hanbang.taitaigou.utils.other.Validators;
import com.hanbang.taitaigou.utils.ui.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 添加地址的页面
 */
public class AboutMeAddAddressManagementActivity extends BaseActivity {


    private EditHelper editHelper = new EditHelper(this);
    public static int CITY_SELECT_FLAG = 1992;
    public static String ADDRESS_CHANG = "AddressUpdataActivity_ADDRESS_CHANG";

    public LocationClient mLocationClient = null;
    public BDLocationListener myListener = new MyLocationListener();


    private String selectSf = "";
    private String selectCity = "";
    private String selectQuyu = "";
    /**
     * 标记是更新还是新增 1:新增，2：更新
     */
    private int type = 0;
    private int id = 0;
    private int addType = 0;
    //经度
    private double locationLng;
    //纬度
    private double locationLat;

    private Geocoder geocoder = null;

    private AboutMeAddressManagemenntActivity addAddress;
    private AddAddressActivity addAddressMain;

    boolean b= true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initBaiduLocation();
        type = getIntent().getIntExtra("type", type);
        addType = getIntent().getIntExtra("addType",addType);
        id = getIntent().getIntExtra("id", id);
        setContentView(R.layout.aboutme_add_address);
        initView();
        setOnClickListener();
    }

    public void initBaiduLocation() {

        mLocationClient = new LocationClient(getApplicationContext());     //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);    //注册监听函数
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        option.setScanSpan(0);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(true);//可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);//可选，默认false，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤gps仿真结果，默认需要
        mLocationClient.setLocOption(option);
    }

    /*
     * 设置点击事件
     */
    private void setOnClickListener() {

    }

    @SuppressWarnings("unused")
    private OnClickListener onClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {

                default:
                    break;
            }
        }
    };

    /*
     * 初始化view
     */
    private void initView() {
        // 设置顶部的标题

        if (type == 1) {
            setTop(null, 0, getString(R.string.top_add_address_management), null, 0);
        } else {
            setTop(null, 0, getString(R.string.top_modify_address_management), null, 0);
        }
        setBackArrows(findViewById(R.id.top_bar_left_iv));
        editHelper.setEditText(name, phone, address, xiangAddress);
        editHelper.setHintText("请输入2-10个字的名字", "请输入正确的手机号", "请选择联系地址", "请输入5-40个字的街道");
        editHelper.setRegEx("[\\S]{2,10}", Validators.REGEX_PHONE_NUMBER, "[\\S]+", "[\\S]{5,40}");

        /**
         * 如果是更新，，那么就把前面的界面带过来的数据填充上
         */
        if (type == 2) {
            name.setText(getIntent().getStringExtra("name"));
            phone.setText(getIntent().getStringExtra("phone"));
            selectSf = getIntent().getStringExtra("sf");
            selectCity = getIntent().getStringExtra("city");
            selectQuyu = getIntent().getStringExtra("quyu");
            address.setText(selectSf + selectCity + selectQuyu);
            xiangAddress.setText(getIntent().getStringExtra("xiangAddress"));
        }

    }

    /**
     * 保存的点击事件
     */
    @Event(value = R.id.button, type = OnClickListener.class)
    private void baocunOnClick(View view) {

        /**
         * 判断是否登录
         */
        if (!isLogin(true)) {
            return;
        }
        /**
         * 判断输入是否合法
         */
        if (editHelper.check()) {
            postAddress();
//            dzzjw();
        }
    }

    /**
     * 新增地址，或者更新地址
     * mobile	string	手机号码
     * tp_password	string	验证码登录时用的临时密码
     * id	int	收货地址ID编号
     * province	string	省份名称
     * city	string	城市名称
     * area	string	区域名称
     * address	sring	详细地址
     * purchname	sring	联系人
     * purchtel	sring	联系电话
     * lng	decimail	经度
     * lat	decimial	纬度
     */
    private void postAddress() {
        if(addType == 1) {
            for (int i = 0; i < addAddress.list.size(); i++) {
                if ((addAddress.list.get(i).getProvince()
                        + addAddress.list.get(i).getCity()
                        + addAddress.list.get(i).getArea()
                        + addAddress.list.get(i).getAddress())
                        .equals(address.getText().toString().trim() + xiangAddress.getText().toString().trim())) {
                    ToastUtils.showShort(AboutMeAddAddressManagementActivity.this, "已有该地址，不可重复添加...");
                    return;
                }
            }
        }else if (addType == 2){
            for (int i = 0; i < addAddressMain.addressList.size(); i++) {
                if (( addAddressMain.addressList.get(i).getProvince()
                        +  addAddressMain.addressList.get(i).getCity()
                        +  addAddressMain.addressList.get(i).getArea()
                        +  addAddressMain.addressList.get(i).getAddress())
                        .equals(address.getText().toString().trim() + xiangAddress.getText().toString().trim())) {
                    ToastUtils.showShort(AboutMeAddAddressManagementActivity.this, "已有该地址，不可重复添加...");
                    return;
                }
            }
        }

        if(b){
            dzzjw();
            String action = type == 1 ? "AddUserAddress" : "UpdateUserAddress";
            HttpRequestParams params = new HttpRequestParams(action);
            params.addUserId(userData);
            params.addBodyParameter("province", selectSf);
            params.addBodyParameter("city", selectCity);
            params.addBodyParameter("area", selectQuyu);
            params.addBodyParameter("address", editHelper.getText().get(3));
            params.addBodyParameter("purchname", editHelper.getText().get(0));
            params.addBodyParameter("purchtel", editHelper.getText().get(1));
            params.addBodyParameter("lng", String.valueOf(locationLng));
            params.addBodyParameter("lat", String.valueOf(locationLat));
            if (type == 2) {
                params.addBodyParameter("id", String.valueOf(id));

            }

            httpManager.post(params, new HttpCallBack<String>(this, null) {

                @Override
                public void onSuccess(String result) {
                    super.onSuccess(result);
                    try {
                        JSONObject json = new JSONObject(result);
                        ToastUtils.showShort(AboutMeAddAddressManagementActivity.this, json.getString("msg"));
                        if (json.getInt("status") == 1) {
                            sendBroadcast(new Intent(ADDRESS_CHANG));
                            Intent intent = new Intent();
                            setResult(1001, intent);
                            finish();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        b=false;


    }

    /**
     * 定位点击事件
     */
    @Event(value = R.id.ll_about_me_add_address_current_location, type = OnClickListener.class)
    private void dingWeiOnClick(View view) {
        if (!mLocationClient.isStarted()) {
            mLocationClient.start();
        }

    }

    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            mLocationClient.stop();
            if (bdLocation.getLocType() == BDLocation.TypeGpsLocation || bdLocation.getLocType() == BDLocation.TypeNetWorkLocation) {
                //gps或者网络  定位成功
                locationLng = bdLocation.getLongitude();
                locationLat = bdLocation.getLatitude();

                //省份
                selectSf = bdLocation.getProvince();
                selectCity = bdLocation.getCity();
                selectQuyu = bdLocation.getDistrict();
                address.setText(selectSf + selectCity + selectQuyu);
                //街道
                String jd = "";
                if (!StringUtils.isBlank(bdLocation.getStreet())) {
                    jd += bdLocation.getStreet();
                }
                if (!StringUtils.isBlank(bdLocation.getStreetNumber())) {
                    jd += bdLocation.getStreetNumber();
                }
                xiangAddress.setText(jd);
                List<Poi> pois = bdLocation.getPoiList();

                if (pois != null && pois.size() > 0) {
                    ArrayList<String> pp = new ArrayList<>();
                    for (Poi p : pois) {
                        pp.add(p.getName());
                    }
                    pois = null;
                    //弹出对话框选择
                    BaseDialog dialog = new BaseDialog(AboutMeAddAddressManagementActivity.this, R.style.base_dialog, BaseDialog.MODE.SELECT);
                    dialog.setSelectData(pp);
                    SpannableString ss = new SpannableString("选择附近点\n" + selectSf + selectCity + selectQuyu);
                    //前景色
                    ss.setSpan(
                            new ForegroundColorSpan(getResources().getColor(
                                    R.color.gray_text)), 5,
                            ss.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                    //相对大小
                    ss.setSpan(
                            new RelativeSizeSpan(0.74f), 5,
                            ss.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);

                    dialog.setTitleMain(ss);
                    dialog.setOnClickCallback(new OnClickCallback() {

                        @Override
                        public void onClick(BaseDialog dialog, Object number, Object content) {
                            if ((Integer) number >= 0) {
                                xiangAddress.setText(content.toString());
                            }
                        }
                    });
                    dialog.show();
                }
            } else {
                //定位失败
                ToastUtils.showShort(AboutMeAddAddressManagementActivity.this, "定位失败");
            }
        }
    }

    /**
     * 城市选择点击
     */
    @Event(value = R.id.et_about_me_add_address_shipping_address, type = OnClickListener.class)
    private void addressOnClick(View view) {
        Intent intent = new Intent(this, CitySelectActivity.class);
        startActivityForResult(intent, CITY_SELECT_FLAG);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CITY_SELECT_FLAG && resultCode == CITY_SELECT_FLAG) {
            selectSf = data.getStringExtra("sf");
            selectCity = data.getStringExtra("city");
            selectQuyu = data.getStringExtra("quyu");
            address.setText(selectSf + selectCity + selectQuyu);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @ViewInject(value = R.id.et_about_me_add_address_name)
    private EditText name;

    @ViewInject(value = R.id.et_about_me_add_address_tel)
    private EditText phone;

    @ViewInject(value = R.id.et_about_me_add_address_shipping_address)
    private TextView address;

    @ViewInject(value = R.id.et_about_me_add_address_specific_address)
    private EditText xiangAddress;

    @ViewInject(value = R.id.ll_about_me_add_address_current_location)
    private EditText dingwei;


    /**
     * 获取地址的经纬度
     */
    public void dzzjw() {

        try {
            String aa = (address.getText().toString() + xiangAddress.getText().toString());
            geocoder = new Geocoder(this);
            List<Address> addressList = geocoder.getFromLocationName(aa, 7);
            if (addressList != null && addressList.size() > 0) {
                locationLng = addressList.get(0).getLongitude();
                locationLat = addressList.get(0).getLatitude();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
